# Maestro is a music database search utility
# Copyright (C) 2010 Robert Mens
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

from __future__ import print_function

import sys, string
import settings, scanner

class CliInterface():
    def __init__(self):
        self.player = settings.player

    def search_song(self, query, silent=False, ask=False, enqueue=False, verbose=False, play_id=0, filenames=False):
        results = settings.mdb.get_songs(query)

        play = True
        result_counter = 0
        
        if silent:
            play = False
            ask = False
        if enqueue:
            ask = False
            
        if results:
            if filenames:
                for result in results:
                    print(result[1])
            else:
                print("Maestro %s - Found Songs:\n" % settings.version)

                result_padding = len(str(len(results)))
                for result in results:
                    result_counter += 1
                    if result:
                        if verbose:
                            print("Result ID: %s\nFilename: %s\nTitle: %s\nArtist: %s\nAlbum: %s\nTrack: %s\n" % (str(result_counter), result[1], result[2], result[3], result[4], result[5]))
                        else:
                            id = "["+str(result_counter).rjust(result_padding)+"]"
                            if not result[3] and not result[2]:
                                print("%s %s" % (id, result[1]))
                            else:
                                print("%s %s - %s" % (id, result[3], result[2]))

                if play_id > 0:
                    if play_id < (len(results) + 1):
                        filename = results[play_id - 1][1]
                        if enqueue:
                            self.player.enqueue([filename])
                        else:
                            self.player.play([filename])
                    else:
                        print("Invalid result id")
                else:   
                    if len(results) == 1:
                        filename = results[0][1]
                        if ask:
                            choice = raw_input("\nPlay Y/e/n ?").lower()
                            if choice == '' or choice == 'y': self.player.play([filename])
                            elif choice == 'e': self.player.enqueue([filename])
                        else:
                            self.player.enqueue([filename])
                    else:
                        play_files = []
                        enqueue_files = []
                        
                        choice = raw_input("\nPlay N/[e]a/(range)? ").lower()
                        choice = "".join(choice.split()) # remove string.whitespace

                        if choice == '' or choice == 'n': sys.exit(0)

                        choices = choice.split(',')

                        for choice in choices:
                            if choice == '': continue
                            filenames = []
                            enqueue = False
                            if choice[0] == 'e':
                                enqueue = True
                                choice = choice[1:]

                            if choice == '' or choice == 'a':
                                for result in results:
                                    filenames.append(result[1])    
                            else:
                                if choice.isdigit():
                                    choice = int(choice)
                                    if choice > 0 and choice <= len(results):
                                        filenames.append(results[int(choice - 1)][1])
                                    else:
                                        print("Invalid result id")
                                else:
                                    tmp_numbers = choice.split('-')
                                    numbers = []
                                    
                                    for number in tmp_numbers:
                                        if not number.isdigit():
                                            print("Invalid result id in range (not a digit)")
                                            sys.exit(1)
                                        else:
                                            numbers.append(int(number))

                                    if len(numbers) == 2 and numbers[0] < numbers[1]:
                                        if numbers[0] > 0 and numbers[0] <= len(results):
                                            if numbers[1] > 0 and numbers[1] <= len(results):
                                                for i in range(numbers[0], numbers[1] + 1):
                                                    filenames.append(results[i - 1][1])
                                    else: 
                                        print("invalid range specified")
                                        sys.exit(1)

                            if enqueue == True:
                                enqueue_files.extend(filenames)
                            else:
                                play_files.extend(filenames)

                        if not len(play_files) == 0: self.player.play(play_files)
                        if not len(enqueue_files) == 0: self.player.enqueue(enqueue_files)
        else:
            if not filenames: print ("Maestro - %s\n\nNo results" % settings.version)
                

    def clean_db(self):
        files = scanner.scan_for_missing_files()
        if files:
            print("The following files were removed from the database because they don't exist anymore:")
            for filename in files:
                print(filename)
        else:
            print("No files were removed from the database")




